package com.yklab.library.json;

import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.JsonParser;

import java.util.List;

public class JSONUtil {

    /**
     * describe:Object转Json
     * author:czhang
     * date:2017/5/27 15:33
     */
    public static String toJSON(Object obj) {
        return new Gson().toJson(obj);
    }
    /*public static Object parseString(String reps) {
        return JSON.parse(reps);
    }*/

    /**
     * describe:字符串转Object
     * author:czhang
     * date:2017/5/27 15:33
     */
    public static <T> T parseObject(String text, Class<T> clazz) {
        //return new Gson().fromJson(text, clazz);
        return JSON.parseObject(text, clazz);
    }

    /**
     * describe:json字符串转List
     * author:czhang
     * date:2017/5/27 15:32
     */
    public static <T> List<?> parseArray(String text, final Class<?> clazz) {
        /*return new Gson().fromJson(text, new TypeToken<List<?>>() {
        }.getType());*/
        return JSON.parseArray(text, clazz);
    }

    /**
     * describe:验证Json字符串合法性
     * author:czhang
     * date:2017/5/27 15:32
     */
    public static boolean isJsonFormat(String jsonContent) {
        if (TextUtils.isEmpty(jsonContent) || !jsonContent.contains("{")) {
            return false;
        }
        try {
            new JsonParser().parse(jsonContent);
            return true;
        } catch (Exception e) {
            return false;
        }
    }


    /**
     * string转json
     *
     * @param jsonContent
     * @return
     */
    public static JSONObject stringToJSon(String jsonContent) {
        return JSON.parseObject(jsonContent);
    }
}

